package com.htfyun.roobofactory;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.htfyun.roobofactory.config.AppConfig;
import com.htfyun.roobofactory.config.RooboBuildConfig;
import com.htfyun.roobofactory.config.RooboProperty;
import com.htfyun.roobofactory.engineerTest.EngineerTestMainActivity;
import com.htfyun.roobofactory.factorytest.FactoryTestItemsEnum;
import com.htfyun.roobofactory.factorytest.FactoryTestMainActivity;
import com.htfyun.roobofactory.htfyunUtils.BatteryInfo;
import com.htfyun.roobofactory.htfyunUtils.NvDataTool;
import com.roobo.common.utils.Utils;
import com.roobo.hardware.LedCtrlManager;
import com.roobo.hardware.RockChipSn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.htfyun.roobofactory.htfyunUtils.MakeTimeUtils.makeTimeString;


public class MainActivity extends BaseActivity {

    private View btnLayout;
    private View layoutRight;
    private Button btnSystemLauncher;
    private Button btnEngineerTest;
    private Button btnAutoTest;
    private Button btnFactoryTest;

    private TextView txtNoBsnInfo;

    private TextView txtWelcome;
    private ListView listViewInfo;

    private InfoAdapter infoAdapter;

    private BatteryInfo batteryInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        batteryInfo = new BatteryInfo(this);

        txtWelcome = (TextView) findViewById(R.id.txtWelcome);
        listViewInfo = (ListView) findViewById(R.id.listViewInfo);

        btnLayout = findViewById(R.id.btnLayout);
        layoutRight = findViewById(R.id.layoutRight);

        txtNoBsnInfo = (TextView) findViewById(R.id.txtNoBsnInfo);

        txtWelcome.setText(getString(R.string.welcome, AppConfig.VERSION_NAME));

        btnSystemLauncher = (Button) findViewById(R.id.btnSystemLauncher);
        btnEngineerTest = (Button) findViewById(R.id.btnEngineerTest);
        btnAutoTest = (Button) findViewById(R.id.btnAutoTest);
        btnFactoryTest = (Button) findViewById(R.id.btnFactoryTest);

        if (!RooboBuildConfig.HAS_AGING_TEST) {
            btnAutoTest.setVisibility(View.GONE);
        }

        btnSystemLauncher.setOnClickListener(onClickListener);
        btnEngineerTest.setOnClickListener(onClickListener);
        btnAutoTest.setOnClickListener(onClickListener);
        btnFactoryTest.setOnClickListener(onClickListener);

        List<InfoShowAttr> infoShowAttrList = new ArrayList<>();
        for (InfoShowAttr attr : InfoShowAttr.values()) {
            infoShowAttrList.add(attr);
        }

        Collections.sort(infoShowAttrList, new Comparator<InfoShowAttr>() {
            @Override
            public int compare(InfoShowAttr o1, InfoShowAttr o2) {
                return o1.getOrder() - o2.getOrder();
            }

        });

        infoAdapter = new InfoAdapter(this, -1, infoShowAttrList);

        listViewInfo.setAdapter(infoAdapter);

    }

    @Override
    protected void onResume() {
        super.onResume();

        String allString = NvDataTool.getInstance().getAllStringInfoFromNVRomData(0, NvDataTool.getInstance().getCountOfAllStringInfo());
        Log.i(TAG, "all string = " + allString);

        String allInteger = NvDataTool.getInstance().getAllIntegerInfoFromNVRomData(0, NvDataTool.getInstance().getCountOfAllIntegerInfo());
        Log.i(TAG, "all integer = " + allInteger);



        batteryInfo.startMonitor();
        batteryInfo.setOnBatteryChangedListener(new BatteryInfo.OnBatteryChangedListener() {
            @Override
            public void onBatteryChangedListener() {
                infoAdapter.notifyDataSetChanged();
            }
        });

        infoAdapter.notifyDataSetChanged();

        if (!RooboBuildConfig.FT_IGNORE_BSN_BURNT) {

            RockChipSn rockChipSn = RockChipSn.getInstance();
            String bsn = rockChipSn.getBSN();

            if (TextUtils.isEmpty(bsn) || (bsn.compareToIgnoreCase("null") == 0)) {

                String pcbaResult = NvDataTool.getInstance().getPCBAResult();
                Log.e(TAG, "pcbaResult = " + pcbaResult);
                if (TextUtils.isEmpty(pcbaResult) || pcbaResult.contains("fail") || pcbaResult.contains("MA")) {
                    txtNoBsnInfo.setText(R.string.main_warning_no_pcba_test);
                } else {
                    txtNoBsnInfo.setText(R.string.main_warning_no_bsn);
                }

                txtNoBsnInfo.setVisibility(View.VISIBLE);
                btnLayout.setVisibility(View.GONE);
                layoutRight.setBackgroundColor(getColor(R.color.lightRed));

            } else {

                txtNoBsnInfo.setVisibility(View.GONE);
                btnLayout.setVisibility(View.VISIBLE);
                layoutRight.setBackgroundColor(getColor(R.color.lightGray));

            }
        } else {

            txtNoBsnInfo.setVisibility(View.GONE);
            btnLayout.setVisibility(View.VISIBLE);
            layoutRight.setBackgroundColor(getColor(R.color.lightGray));

        }

    }

    @Override
    protected void onPause() {
        super.onPause();

        batteryInfo.setOnBatteryChangedListener(null);
        batteryInfo.stopMonitor();

    }

    private View.OnClickListener  onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (v == btnSystemLauncher) {

                startDefaultHome();

            } else if (v == btnEngineerTest) {

                startActivity(new Intent(MainActivity.this, EngineerTestMainActivity.class));

            } else if (v == btnAutoTest) {

                startActivity(new Intent(MainActivity.this, AgingTestActivity.class));


            } else if (v == btnFactoryTest) {
                startActivity(new Intent(MainActivity.this, FactoryTestMainActivity.class));

            }

        }
    };

    private void startDefaultHome() {
        ComponentName comp = ComponentName.unflattenFromString(RooboBuildConfig.DEFAULT_LAUNCHER);
        Intent intent = new Intent();
        intent.setComponent(comp);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

        if (list.size() <= 0) {
            Toast.makeText(this, R.string.comp_not_exist, Toast.LENGTH_LONG).show();
            return;
        }
        startActivity(intent);
    }


    private final class InfoAdapter extends ArrayAdapter<InfoShowAttr> {
        public InfoAdapter(@NonNull Context context, int resource, @NonNull List<InfoShowAttr> objects) {
            super(context, resource, objects);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView != null) {

                holder = (ViewHolder) convertView.getTag();

            } else {

                holder = new ViewHolder();
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_info, null);
                holder.txt = (TextView) convertView.findViewById(R.id.txtInfo);

                convertView.setTag(holder);
            }

            InfoShowAttr attr = getItem(position);

            if (attr != null) {

                InfoShowText infoShowText = getStringByInfoShowAttr(attr);
                holder.txt.setTextColor(infoShowText.color);
                holder.txt.setText(infoShowText.txt);
            }

            return convertView;
        }
    }


    private final class ViewHolder {
        TextView txt;
    }

    private InfoShowText getStringByInfoShowAttr(InfoShowAttr attr) {

        int colorBlack = getColor(R.color.colorBlack);
        int colorBlue = getColor(R.color.colorBlue);
        int colorRed = getColor(R.color.colorRed);
        String notExist = getString(R.string.info_not_exist);

        String txt = "";
        int color = colorBlack;

        RockChipSn rockChipSn = RockChipSn.getInstance();

        switch (attr) {
            case bsn: {

                txt = getString(attr.getStringResId(), rockChipSn.getBSN());
                color = colorBlue;

                if (0 == rockChipSn.getBSN().compareToIgnoreCase("null")) {
                    color = colorRed;
                }

                break;
            }
            case sn:{
                txt = getString(attr.getStringResId(), rockChipSn.getSN());
                color = colorBlue;

                if (0 == rockChipSn.getSN().compareToIgnoreCase("null")) {
                    color = colorRed;
                }

                break;
            }
            case wifiMac:{

                txt = getString(attr.getStringResId(), rockChipSn.getWifiMac());

                color = colorBlue;

                break;
            }
            case all_tested:{

                boolean allOk = true;
                for (FactoryTestItemsEnum item : FactoryTestItemsEnum.values()) {
                    if (!item.isPassed(getActivity())) {
                        allOk = false;
                        break;
                    }
                }

                int resId = allOk ?
                        R.string.all_tested_completed : R.string.all_tested_not_completed;
                txt = getString(attr.getStringResId(), getString(resId));

                if (allOk) {
                    color = colorBlue;
                } else {
                    color = colorRed;
                }


                break;
            }
            case proximity_sensor: {
                boolean isNoise = NvDataTool.getInstance().isProximitySensorNoiseSet();
                boolean isDiff = NvDataTool.getInstance().isProximitySensorDifferenceSet();
                String status = getString(R.string.proximity_sensor_not_calibrated);
                color = colorRed;
                if (isNoise && isDiff) {
                    int noise = NvDataTool.getInstance().getProximitySensorNoise();
                    int diff = NvDataTool.getInstance().getProximitySensorDifference();
                    status = getString(R.string.proximity_sensor_calibrated, noise, diff);
                    color = colorBlue;

                }

                txt = getString(attr.getStringResId(), status);

                break;
            }
            case cx20921: {
                String cx20921Ver = Utils.getSystemProperty(RooboProperty.CX20921_UPDATED_PROP);

                String val = getString(R.string.cx20921_not_updated);
                color = colorRed;

                if (!TextUtils.isEmpty(cx20921Ver)) {
                    val = getString(R.string.cx20921_updated, cx20921Ver);
                    color = colorBlue;
                }

                txt = getString(attr.getStringResId(), val);

                break;
            }
            case pc_checked:

                String status = getString(R.string.pc_test_unchecked);
                color = colorRed;
                if (NvDataTool.getInstance().isFactoryTestChecked()) {
                    status = getString(R.string.pc_test_checked);
                    color = colorBlue;
                }
                txt = getString(R.string.info_pc_checked, status);

                break;
            case led:
                LedCtrlManager ledCtrlManager = LedCtrlManager.getInstance();
                txt = getString(attr.getStringResId(),
                        ledCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_LEFT),
                        ledCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_RIGHT));

                break;

            case battery: {

                txt = getString(attr.getStringResId(),
                        batteryInfo.getBatteryVoltage(),
                        batteryInfo.getBatteryLevel(),
                        batteryInfo.getBatteryStatusString());

                break;
            }
            case aging: {

                SharedPreferences sp = getActivity().getSharedPreferences(AppConfig.SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
                long time = sp.getLong(AppConfig.SHARE_PREFERENCE_KEY_AGING_TIME, 0);
                long second = time / 1000;
                String stringTime = makeTimeString(getActivity(), second);
                txt = getString(attr.getStringResId(), stringTime);

                break;
            }
            default:
                break;


        }

        return new InfoShowText(txt, color);

    }

    private class InfoShowText{
        final String txt;
        final int color;

        public InfoShowText(String txt, int color) {
            this.txt = txt;
            this.color = color;
        }
    }

    private enum InfoShowAttr {
        //之所以把order间隙弄那么大, 是为了在其中间插入其他属性值
        bsn(0, R.string.info_bsn),
        sn(10, R.string.info_sn),
        wifiMac(20, R.string.info_wifi_mac),
        all_tested(30, R.string.info_all_tested),
        proximity_sensor(40, R.string.info_proximity_sensor),
        cx20921(50, R.string.info_cx20921),
        pc_checked(60, R.string.info_pc_checked),
        led(70, R.string.info_led),
        battery(80, R.string.info_battery),
        aging(90, R.string.info_aging),

        ;

        private final int order;
        private final int stringResId;

        private InfoShowAttr(int order, int stringResId) {
            this.order = order;
            this.stringResId = stringResId;
        }

        public int getOrder() {
            return order;
        }

        public int getStringResId() {
            return stringResId;
        }

    }

}
